package com.noble.meether.chat.ui.agora.act;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.library.utils.NoDoubleClickListener;
import com.noble.library.image.ImageLoader;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.utils.BitmapUtil;
import com.noble.library.utils.UIUtil;
import com.noble.library.view.custom.state.CustomFrameLayout;
import com.noble.meether.R;
import com.noble.meether.chat.ui.agora.RtcUIShow;
import com.noble.meether.chat.ui.agora.act.base.RtcBaseActivity;
import com.noble.meether.chat.ui.agora.act.bean.Accept;
import com.noble.meether.chat.ui.agora.model.AgoraConstant;
import com.noble.meether.chat.ui.agora.util.RtcJointChannel;
import com.noble.meether.chat.ui.agora.util.RtcSubUtil;
import com.noble.meether.chat.ui.agora.util.RtcTimerUtil;
import com.noble.meether.chat.ui.agora.util.RtcUtil;

import java.util.Map;

/**
 * 邀请 / 受邀 / 音频通话页面
 */
public class RtcInitActivity extends RtcBaseActivity implements PObserver, RequestComplete {

    private LinearLayout chatWaiting;        // 等待通话
    private TextView chatBeInvited;          // 被邀请人提示
    private ImageView imgBg;                 // 背景头像
    private ImageView imgHead;               // 头像
    private TextView tvName;                 // 昵称
    private CustomFrameLayout bottomLayout;  // 底部状态布局切换
    private Chronometer inviteCountUp, chatCountUp;

    private boolean isRelease = true;      // 是否释放资源标志：当需要跳到视频页面时，无需释放资源

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.p1_chat_wait);
        addListener();
        initView();
        initBottom();
    }

    private void initView() {
        RtcUtil.getInstance().resetSynchStatus();   // 重置挂断状态
        chatWaiting = findViewById(R.id.chat_waiting);
        chatBeInvited = findViewById(R.id.chat_be_invited);
        findViewById(R.id.iv_shrink_narrow).setOnClickListener(listener);

        // 个人信息
        imgBg = findViewById(R.id.iv_bg);
        Bitmap bitmap = BitmapUtil.getDecodeBitmap(this, R.drawable.sp_bk, 320, 480);
        UIUtil.setBackground(imgBg, new BitmapDrawable(null, bitmap));
        imgHead = findViewById(R.id.iv_head);
        tvName = findViewById(R.id.tv_name);

        // 计时控件
        inviteCountUp = findViewById(R.id.ch_inv_time);
        chatCountUp = findViewById(R.id.ch_count_time);
        RtcTimerUtil.getInstance().addTimer(inviteCountUp);
        RtcTimerUtil.getInstance().addTimer(chatCountUp);

        findViewById(R.id.btn_invite_hangup).setOnClickListener(listener);
        findViewById(R.id.btn_beinvite_hangup).setOnClickListener(listener);
        findViewById(R.id.btn_answer).setOnClickListener(listener);
        RtcJointChannel.getInstance().reqUserInfo(this);
    }

    /**
     * 同步操作问题
     */
    private void addListener() {
        MsgMgr.getInstance().attach(this);
    }

    private void initBottom() {
        RtcSubUtil.getInstance().playSound();  // 开启铃声
        bottomLayout = findViewById(R.id.frame_layout);
        bottomLayout.showOfIndex(config().mInviteType);

        switch (config().mInviteType) {
            case AgoraConstant.RTC_CHAT_INVITE:   // 邀请
                chatWaiting.setVisibility(View.VISIBLE);
                RtcTimerUtil.getInstance().startStatisInvTime();
                inviteCountUp.setBase(SystemClock.elapsedRealtime() - config().mInviteTime);
                inviteCountUp.start();
                break;

            case AgoraConstant.RTC_CHAT_BEINVITE: // 被邀请
                chatBeInvited.setVisibility(View.VISIBLE);
                if (config().mChatType == AgoraConstant.RTC_CHAT_VOICE) {
                    chatBeInvited.setText(getString(R.string.chat_voice_invite));
                    return;
                }
                chatBeInvited.setText(getString(R.string.chat_video_invite));
                break;
        }
    }

    /**
     * 点击事件
     */
    private NoDoubleClickListener listener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.btn_invite_hangup:   // 邀请方挂断按钮
                case R.id.btn_beinvite_hangup: // 被邀请方拒绝按钮
                    RtcUtil.getInstance().setHandleUp();
                    ModuleMgr.getRtcChatMgr().sendRejectMsg(config().mOtherId, config().mChatType, null);
                    break;

                case R.id.btn_answer:          // 被邀请方接听按钮
                    RtcJointChannel.getInstance().acceptChat(RtcInitActivity.this);
                    break;

                case R.id.iv_shrink_narrow: // 最小化
                    if (checkOverLaysPermission())
                        ModuleMgr.getRtcEnginMgr().startRtcFloatService();
                    break;
            }
        }
    };

    /**
     * 通信跳转
     */
    private void startChat() {
        isRelease = false;
        RtcJointChannel.getInstance().joinChannelPrepare(true);
        if (config().mChatType == AgoraConstant.RTC_CHAT_VIDEO)
            RtcUIShow.showRtcVideoAct(this, true);
        else
            RtcUIShow.showRtcVoiceAct(this, true);
    }

    /**
     * 通话状态消息
     */
    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_Rtc_Chat_Status:
                Map<String, Object> data = (Map<String, Object>) value;
                switch ((int) data.get("type")) {
                    case AgoraConstant.RTC_MSG_ACCEPT:     // 同意加入
                        startChat();
                        break;

                    case AgoraConstant.RTC_MSG_REJECT:     // 拒絕加入
                    case AgoraConstant.RTC_MSG_HANGON:     // 挂断
                    default:
                        finish();
                        break;
                }
                break;

            case MsgType.MT_Rtc_Chat_Close_Msg:
                finish();
                break;
        }
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        if (response.getUrlParam() == UrlParam.reqMyInfo) {
            if (!response.isOk()) return;
            UserDetail userDetail = (UserDetail) response.getBaseData();
            ImageLoader.loadBlur(this, userDetail.getAvatar(), imgBg, 8, R.drawable.sp_bk);
            ImageLoader.loadRoundAvatar(this, userDetail.getAvatar(), imgHead);
            tvName.setText(userDetail.getNickname());
            return;
        }

        // 接受邀请
        if (response.getUrlParam() == UrlParam.reqAcceptChat) {
            if (response.isOk()) {
                Accept accept = (Accept) response.getBaseData();
                config().mChannelKey = accept.getChannelKey();  // 保存到配置文件
                config().mChannel = accept.getChannelName();
                config().mVcid = accept.getVcId();
                startChat();
                return;
            }
            PToast.showShort(response.getMsg() == null ? getString(R.string.chat_join_fail_tips) : response.getMsg());
            ModuleMgr.getRtcChatMgr().sendRejectMsg(config().mOtherId, config().mChatType, null);
        }
    }

    @Override
    public void finish() {
        super.finish();
        LoadingDialog.closeLoadingDialog();
        MsgMgr.getInstance().detach(this);
        RtcSubUtil.getInstance().stopPlay();

        // 处于悬浮窗、跳到视频页面， 则只需释放本地Timer计时
        if (RtcJointChannel.getInstance().getFloatStatus() || !isRelease) {
            ModuleMgr.getRtcEnginMgr().releaseLocalTimer();
            return;
        }

        // 全部回收
        ModuleMgr.getRtcEnginMgr().releaseAll();
    }
}
